﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Jskp.Framework
{
    public static class StringHelper
    {
        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(this string s, string charset = "utf-8", bool fenge = false)
        {
            try
            {
                Encoding chs = Encoding.GetEncoding(charset);
                byte[] bytes = chs.GetBytes(s);
                string str = "";
                for (int i = 0; i < bytes.Length; i++)
                {
                    str += string.Format("{0:x2}", bytes[i]);
                }
                return str.ToUpper();
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 字符串转base64
        /// </summary>
        /// <param name="s">待转字符串</param>
        /// <returns></returns>
        public static string ToBase64(this string s, string encoding = "utf-8")
        {
            byte[] b = System.Text.Encoding.GetEncoding(encoding).GetBytes(s);
            string dest_str = Convert.ToBase64String(b);

            return dest_str;
        }

        /// <summary>
        /// base64转字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FromBase64(this string s, string encoding = "utf-8")
        {
            byte[] b = Convert.FromBase64String(s);

            return System.Text.Encoding.GetEncoding(encoding).GetString(b);
        }

        /// <summary>
        /// 判断是否为URL
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        public static bool IsUrl(string str)
        {
            try
            {
                if (str.ToLower().Contains("http://") || str.ToLower().Contains("https://"))
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 判断是否为汉字
        /// </summary>
        /// <param name="StrChineseString"></param>
        /// <returns></returns>
        public static bool IsChinese(this string StrChineseString)
        {
            return Regex.IsMatch(StrChineseString, @"^[\u4e00-\u9fa5]+$");
        }

        /// <summary>
        /// 字符串转二进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToBinary(this string s)
        {
            byte[] data = Encoding.Unicode.GetBytes(s);
            StringBuilder result = new StringBuilder(data.Length * 8);

            foreach (byte b in data)
            {
                result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
            }
            return result.ToString();
        }

        /// <summary>
        /// 字符串转为decimal数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this string s)
        {
            try
            {
                if (string.IsNullOrEmpty(s.Trim()))
                {
                    return 0;
                }
                else
                {
                    return decimal.Parse(s);
                }
            }
            catch
            {
                return 0;
            }
        }
        

        public static int ToInt(this string s)
        {
            try
            {
                if (string.IsNullOrEmpty(s.Trim()))
                {
                    return 0;
                }
                else
                {
                    return int.Parse(s);
                }
            }
            catch
            {
                return 0;
            }
        }

        public static decimal ToDecimal(this decimal? d)
        {
            return d == null ? decimal.Zero : (decimal)d;
        }

        /// <summary>
        /// 判断字符串是否为正整数
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsInt(this string s)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
            return reg1.IsMatch(s);
        }

        /// <summary>
        /// 空白转零
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string SpaceToZero(this string s)
        {
            if (string.IsNullOrEmpty(s)) return "0.00";
            else if (s == "------" || s == "---" || s == "--------") return "";
            return s;
        }


        #region 字符串数字的加减运算

        /// <summary>
        /// 字符串数字相加（至少需要2个字符串参数）
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static string Add(params string[] values)
        {
            decimal result = 0;

            if (values == null || values.Length < 2)
            {
                throw new ArgumentException("参数个数异常！");
            }

            for (int i = 0; i < values.Length; i++)
            {
                result += decimal.Parse(values[i]);
            }

            return result.ToString("0.00");
        }

        /// <summary>
        /// 加法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static decimal Add(params decimal?[] values)
        {
            decimal result = 0;

            for (int i = 0; i < values.Length; i++)
            {
                result += values[i] ?? 0;
            }

            return result;
        }

        /// <summary>
        /// 加法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static decimal Add(params decimal[] values)
        {
            decimal result = 0;

            for (int i = 0; i < values.Length; i++)
            {
                result += values[i];
            }

            return result;
        }

        /// <summary>
        /// 加法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static decimal Add(params object[] values)
        {
            decimal result = 0;

            for (int i = 0; i < values.Length; i++)
            {
                decimal value = 0;

                decimal.TryParse(values[i]?.ToString(), out value);

                result += value;
            }

            return result;
        }

        /// <summary>
        /// 做减法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static string Minus(params string[] values)
        {
            decimal result = 0;

            if (values == null || values.Length < 2)
            {
                throw new ArgumentException("参数个数异常！");
            }

            for (int i = 0; i < values.Length; i++)
            {
                if (i == 0)
                {
                    result = decimal.Parse(values[i]);
                }
                else
                { 
                    result -= decimal.Parse(values[i]);
                }
            }

            return result.ToString("0.00");
        }

        /// <summary>
        /// 做减法
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static decimal Minus(params decimal?[] values)
        {
            decimal result = 0;

            if (values == null || values.Length < 2)
            {
                throw new ArgumentException("参数个数异常！");
            }

            for (int i = 0; i < values.Length; i++)
            {
                if (i == 0)
                {
                    result = (values[i] == null ? 0 : (decimal)values[i]);
                }
                else
                {
                    result -= (values[i] == null ? 0 : (decimal)values[i]);
                }
            }

            return result;
        }

        #endregion

        public static string ZeroAsSpace(this string data)
        {
            if (decimal.TryParse(data, out decimal d) && !decimal.Zero.Equals(d)) return data;

            return string.Empty;
        }

        /// <summary>
        /// 校验是否为数字或字母
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsNumOrChar(string val)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(val.Trim(), "^[0-9a-zA-Z]+$");
        }

        public static bool ChkIsNumber(string val)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(val, @"^[0-9]+(\.[0-9]{1,2})?$");
        }

        /// <summary>
        /// 字符串转时间
        /// </summary>
        /// <param name="dateStr">如：20220217205011</param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string dateStr)
        {
            if (dateStr.Length != 14) throw new Exception("字符串格式错误");
            string year = dateStr.Substring(0, 4);
            string month = dateStr.Substring(4, 2);
            string day = dateStr.Substring(6, 2);
            string hour = dateStr.Substring(8, 2);
            string minute = dateStr.Substring(10, 2);
            string second = dateStr.Substring(12, 2);

            string date = $"{year}-{month}-{day} {hour}:{minute}:{second}";

            return DateTime.Parse(date);
        }

        /// <summary>
        /// 转换为时间格式
        /// </summary>
        /// <param name="dateTimeStr"></param>
        /// <returns></returns>
        public static string ToDateTimeFormat(this string dateTimeStr)
        {
            try
            {
                return DateTime.ParseExact(dateTimeStr, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch
            {
                return dateTimeStr;
            }
        }

        /// <summary>
        /// 转换为日期格式
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static string ToDateFormat(this string dateStr)
        {
            try
            {
                return DateTime.ParseExact(dateStr, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");
            }
            catch
            {
                return dateStr;
            }
        }

        public static string ToTrim(this string val)
        {
            try
            {
                return val.Trim();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 判断输入的字符串是否只包含数字和英文字母
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsNumAndEnCh(string input)
        {
            if (string.IsNullOrEmpty(input)) return true;

            string pattern = @"^[A-Za-z0-9]+$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }

        public static string GetFileNameFromUrl(string url)
        {
            try
            {
                string[] urls = url.Split('/');
                if (urls.Length > 0)
                {
                    string name = urls[urls.Length - 1];
                    return System.Web.HttpUtility.UrlDecode(name, System.Text.Encoding.UTF8);
                }
            }
            catch { }
            return "";
        }
    }
}
